package com.example.jwt.framework.security.service;

import com.example.jwt.common.core.redis.RedisCache;
import com.example.jwt.common.exception.ServiceException;
import com.example.jwt.framework.security.context.AuthenticationContextHolder;
import com.example.jwt.framework.security.core.TokenManager;
import com.example.jwt.framework.security.model.LoginUser;
import com.example.jwt.project.sys.service.ISysUserService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;


/**
 * @version 1.0.0
 * @className: SysLoginService
 * @description: 登录业务
 * @author: LiJunYi
 * @create: 2022/7/27 12:53
 */
@Component
public class SysLoginService
{
    @Autowired
    private TokenManager tokenManager;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysUserService userService;

    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @return 结果
     */
    public String login(String username, String password)
    {
        // 用户验证
        Authentication authentication;
        try
        {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        }
        catch (Exception e)
        {
            if (e instanceof BadCredentialsException)
            {
                throw new ServiceException("用户名密码错误");
            }
            else
            {
                throw new ServiceException(e.getMessage());
            }
        }finally {
            AuthenticationContextHolder.clearContext();
        }
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        // 生成token
        return tokenManager.createToken(loginUser);
    }


}
